package com.weavernorth.util.SendEmail;

import com.sun.mail.util.MailSSLSocketFactory;
import com.weaver.general.BaseBean;
import com.weavernorth.util.Logger4jUtil;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.apache.log4j.Logger;
import weaver.general.Util;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.util.SendEmail
 * @date: 2021/9/8 14:33
 * @description:
 */
public class SmptClient {
    public Logger log = Logger4jUtil.getLoggerByName("/util/SendEmail/");
    public static BaseBean bb = new BaseBean();
    public static String senderHost = Util.null2String(bb.getPropValue("configMail", "senderHost"));//"smtp.qq.com";//邮件发送的服务器
    public static String protocol = Util.null2String(bb.getPropValue("configMail", "protocol"));//邮件协议
    public static String port = Util.null2String(bb.getPropValue("configMail", "port"));//端口
    public static String senderEmail = Util.null2String(bb.getPropValue("configMail", "senderEmail"));//发件人邮箱
    public static String senderPassword = Util.null2String(bb.getPropValue("configMail", "senderPassword"));//发件人邮箱密码(授权码)
//    测试 qq邮箱服务器发送邮件
//    public static String senderHost = "smtp.qq.com";
//    public static String protocol = "smtp";
//    public static String port = "465";
//    public static String senderEmail = "1947209593@qq.com";
//    public static String senderPassword = "ikhjbzpxcmhyfcge";
    /***
     * 发送邮件:普通文本
     * @param addressee 收件人邮箱
     * @param emailTitle 标题
     * @param emailContent 内容
     * @throws GeneralSecurityException
     */
    public static String sendMailBySmpt(String addressee, String emailTitle, String emailContent) {
        String result = "0|success";
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host", senderHost);
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.auth", "true");
        try {
            //设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);//设置信任所有主机
            properties.put("mail.smtp.ssl.enable", "true");//开启ssl加密
            properties.put("mail.smtp.ssl.socketFactory", sf);
            //创建一个session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(senderEmail, senderPassword);
                }
            });
            //开启debug模式
            session.setDebug(true);
            //获取连接对象
            Transport transport = session.getTransport();
            //连接服务器
            transport.connect(senderHost, senderEmail, senderPassword);
            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);
            //邮件发送人
            mimeMessage.setFrom(new InternetAddress(senderEmail));
            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(addressee));
            //邮件标题
            mimeMessage.setSubject(emailTitle);
            //邮件内容
            mimeMessage.setContent(emailContent, "text/html;charset=UTF-8");
            //发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            //关闭连接
            transport.close();
        } catch (Exception ex) {
            result = "1|" + addressee + "|" + ex.getMessage();
        } finally {
            return result;
        }
    }

    /***
     * 发送邮件：带图片及附件
     * imagePath="C:\\Users\\Pictures\\1.jpg";
     * filePath="C:\\Users\\Desktop\\2021-09-06.rar";
     * @param addressee
     * @param emailTitle
     * @param emailContent
     * @param imagePath
     * @param filePath
     * @throws GeneralSecurityException
     */
    public static String sendMailBySmpt(String addressee, String emailTitle, String emailContent, String imagePath, String filePath) {
        String result = "0|success";
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host", senderHost);
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.auth", "true");//需要验证用户名密码
        properties.setProperty("mail.smtp.ssl.enable", "true");//开启ssl加密
        try {
            //设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);//设置信任所有主机
            properties.put("mail.smtp.ssl.socketFactory", sf);

            //1、创建定义整个应用程序所需的环境信息的 Session 对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    //传入发件人的姓名和授权码
                    return new PasswordAuthentication(senderEmail, senderPassword);
                }
            });
            //开启debug模式
            session.setDebug(true);
            //2、通过session获取transport对象
            Transport transport = session.getTransport();
            //3、通过transport对象根据邮箱用户名和授权码连接邮箱服务器
            transport.connect(senderHost, senderEmail, senderPassword);
            //4、创建邮件,传入session对象
            MimeMessage mimeMessage = complexEmail(session, senderEmail,addressee, emailTitle, emailContent, imagePath, filePath);
            //5、发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            //关闭连接
            transport.close();
        } catch (Exception ex) {
            result = "1|" + addressee + "|" + ex.getMessage();
        } finally {
            return result;
        }
    }


    public static MimeMessage complexEmail(Session session,String senderEmail,String addressee, String emailTitle, String emailContent, String imagePath, String filePath) throws MessagingException {
        //消息的固定信息
        MimeMessage mimeMessage = new MimeMessage(session);
        //发件人
        mimeMessage.setFrom(new InternetAddress(senderEmail));
        //收件人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(addressee));
        //邮件标题
        mimeMessage.setSubject(emailTitle);
        //准备图片数据
        MimeBodyPart image = new MimeBodyPart();
        //邮件内容
        DataHandler handler = new DataHandler(new FileDataSource(imagePath));
        image.setDataHandler(handler);
        String imageId = new File(imagePath).getName();
        image.setContentID(imageId); //设置图片id
        if (!"".equals(imageId)) {
            emailContent += "<img src='cid:" + imageId + "'>";
        }
        System.out.println("图片大小：" + image.getSize());

        //准备文本
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(emailContent, "text/html;charset=utf-8");

        //附件
        MimeBodyPart appendix = new MimeBodyPart();
        appendix.setDataHandler(new DataHandler(new FileDataSource(filePath)));
        appendix.setFileName(new File(filePath).getName());


        //拼装邮件正文
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(image);
        mimeMultipart.addBodyPart(text);
        mimeMultipart.setSubType("related");//文本和图片内嵌成功

        //将拼装好的正文内容设置为主体
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent(mimeMultipart);

        //拼接附件
        MimeMultipart allFile = new MimeMultipart();
        System.out.println("附件大小：" + appendix.getSize());
        allFile.addBodyPart(appendix);//附件
        allFile.addBodyPart(contentText);//正文
        allFile.setSubType("mixed"); //正文和附件都存在邮件中，所有类型设置为mixed

        //放到Message消息中
        if (appendix.getSize() > 0) {
            mimeMessage.setContent(allFile);
        } else {
            mimeMessage.setContent(emailContent, "text/html;charset=UTF-8");
        }
        mimeMessage.setSubject(emailTitle);//标题
        mimeMessage.saveChanges();//保存修改

        return mimeMessage;
    }


}
